<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="上级推荐人" prop="superReferralCode">
        <el-select v-model="queryParams.superReferralCode" placeholder="请选择上级推荐人" clearable filterable>
          <el-option
            v-for="item in wxUserList"
            :key="item.referralCode"
            :label="item.nickName"
            :value="item.referralCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="推荐码" prop="referralCode">
        <el-input
          v-model="queryParams.referralCode"
          show-word-limit maxlength="50"
          placeholder="请输入推荐码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="会员状态" prop="disable">
        <el-select v-model="queryParams.disable" placeholder="请选择会员状态" clearable>
          <el-option
            v-for="dict in dict.type.member_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!--      <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="handleAdd"
                v-hasPermi="['funct:member:add']"
              >新增</el-button>
            </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['funct:member:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['funct:member:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-refresh-right"
          size="mini"
          :disabled="multiple"
          @click="openCreateDialog(false)"
          v-hasPermi="['funct:member:add']"
        >重置码</el-button>
      </el-col>
      <!--      <el-col :span="1.5">
              <el-button
                type="warning"
                plain
                icon="el-icon-download"
                size="mini"
                @click="handleExport"
                v-hasPermi="['funct:member:export']"
              >导出</el-button>
            </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="memberList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="用户名称" align="center" prop="userId" :formatter="tranNickName"/>
      <el-table-column label="用户电话" align="center" prop="memberPhone"/>
      <el-table-column label="上级推荐人" align="center" prop="superReferralCode" :formatter="tranSuperReferralCode"/>
      <el-table-column label="推荐码" align="center" prop="referralCode"/>
      <el-table-column label="会员到期时间" align="center" prop="memberExpireDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.memberExpireDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="会员状态" align="center" prop="disable">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.member_status" :value="scope.row.disable"/>
        </template>
      </el-table-column>
      <el-table-column label="推广海报" align="center" prop="recommendedPoster" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.recommendedPoster" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="小程序码" align="center" prop="smallShareQrcode" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.smallShareQrcode" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="可提取天数" align="center" prop="extractableDays"/>
      <el-table-column label="已提取天数" align="center" prop="drawnDays"/>
      <el-table-column label="备注信息" align="center" prop="remark" :show-overflow-tooltip="true"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['funct:member:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['funct:member:remove']"
          >删除
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-refresh-right"
            @click="openCreateDialog(true, scope.row.id)"
            v-hasPermi="['funct:member:edit']"
          >重置码
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改会员管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="65%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="用户昵称" prop="userId">
          <el-select v-model="form.userId" :disabled="true" placeholder="请选择用户昵称" clearable filterable>
            <el-option
              v-for="item in wxUserList"
              :key="item.userId"
              :label="item.nickName"
              :value="item.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="上级推荐人" prop="superReferralCode">
          <el-select v-model="form.superReferralCode" :disabled="true" placeholder="请选择上级推荐人" clearable
                     filterable>
            <el-option
              v-for="item in wxUserList"
              :key="item.referralCode"
              :label="item.nickName"
              :value="item.referralCode"
            />
          </el-select>
        </el-form-item>
        <!--        <el-form-item label="推荐码" prop="referralCode">
                  <el-input v-model="form.referralCode" placeholder="请输入推荐码" />
                </el-form-item>-->
        <el-form-item label="会员到期时间" prop="memberExpireDate">
          <el-date-picker clearable
                          v-model="form.memberExpireDate"
                          type="datetime"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="请选择会员到期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="会员状态" prop="disable">
          <el-select v-model="form.disable" placeholder="请选择会员状态">
            <el-option
              v-for="dict in dict.type.member_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <!--        <el-form-item label="会员推荐海报" prop="recommendedPoster">
                  <image-upload v-model="form.recommendedPoster"/>
                </el-form-item>
                <el-form-item label="会员分享小程序码" prop="smallShareQrcode">
                  <image-upload v-model="form.smallShareQrcode"/>
                </el-form-item>-->
        <el-form-item label="可提取天数" prop="extractableDays">
          <el-input-number v-model="form.extractableDays" :max="50000" placeholder="请输入可提取天数"/>
        </el-form-item>
        <el-form-item label="已提取天数" prop="drawnDays">
          <el-input-number v-model="form.drawnDays" :max="50000" placeholder="请输入已提取天数"/>
        </el-form-item>
        <!--        <el-form-item label="续费时间" prop="renewalTime">
                  <el-date-picker clearable
                    v-model="form.renewalTime"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="请选择续费时间">
                  </el-date-picker>
                </el-form-item>-->
        <el-form-item label="备注信息" prop="remark">
          <el-input v-model="form.remark" show-word-limit type="textarea" rows="3" maxlength="1000"
                    placeholder="请输入备注信息"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改会员管理对话框 -->
    <el-dialog title="码信息重置类型" :visible.sync="createMiniFlag" width="30%" append-to-body>
        码信息重置类型：
        <el-select v-model="createFlag" placeholder="请选择码信息重置类型">
          <el-option
            v-for="dict in dict.type.code_renew_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="createCodeAndPost">确 定</el-button>
        <el-button @click="createMiniFlag = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listMember,
  getMember,
  delMember,
  addMember,
  updateMember,
  listAllWxUser,
  createCodeAndPost,
  createCodeAndPostAll
} from "@/api/funct/member";

export default {
  name: "Member",
  dicts: ['member_status', 'code_renew_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 会员管理表格数据
      memberList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        superReferralCode: null,
        referralCode: null,
        memberExpireDate: null,
        disable: null,
        recommendedPoster: null,
        smallShareQrcode: null,
        extractableDays: null,
        memberPhone: null,
        drawnDays: null,
        renewalTime: null,
        remark: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userId: {type: "number", trigger: "blur", required: true, message: '用户名称不能为空!'},
        referralCode: {type: "string", trigger: "blur", required: true, message: '用户推荐码不能为空!'},
        disable: {type: "string", trigger: "blur", required: true, message: '会员状态不能为空!'}
      },
      wxUserList: [],
      createMiniFlag: false,
      createFlag: '', // 重置类型
      btnFlag: true, // true代表单个，默认为单个;false默认批量重新生成码
      createId: '',
    };
  },
  created() {
    this.getWxUserList();
    this.getList();
  },
  methods: {
    // 查询所有微信用户信息
    getWxUserList() {
      this.loading = true;
      listAllWxUser().then(res => {
        this.wxUserList = res.rows;
        this.loading = false;
      })
    },
    /** 查询会员管理列表 */
    getList() {
      this.loading = true;
      listMember(this.queryParams).then(response => {
        this.memberList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 转换用户名称
    tranNickName(row, column, cellValue) {
      if (this.wxUserList != null && this.wxUserList != undefined && this.wxUserList != undefined) {
        for (let i = 0; i < this.wxUserList.length; i++) {
          if (this.wxUserList[i].userId == cellValue) {
            return this.wxUserList[i].nickName;
          }
        }
      }
    },
    // 转换上级推荐人
    tranSuperReferralCode(row, column, cellValue) {
      if (this.wxUserList != null && this.wxUserList != undefined && this.wxUserList != undefined) {
        for (let i = 0; i < this.wxUserList.length; i++) {
          if (this.wxUserList[i].referralCode == cellValue) {
            return this.wxUserList[i].nickName;
          }
        }
      }
    },
    openCreateDialog(isOne, id) {
      this.createFlag = ''; // 默认清除
      this.btnFlag = isOne;
      this.createMiniFlag = true;
      this.createId = id
      // isOne ? this.createCodeAndPost() : this.createCodeAndPostAll();
    },
    createCodeAndPost() {
      if (!this.createFlag.trim().length) {
        this.$modal.msgWarning("码重置类型不能为空");
        return;
      }
      if (this.btnFlag) {
        // this.btnFlag = true; // 单个
        console.log("单个会员信息重新生成二维码");
        createCodeAndPost(this.createId, this.createFlag).then(res => {
          if (res.code == 200) {
            this.getList();
            this.$modal.msgSuccess("重新生成成功！");
          }
        })
      } else {
        // this.btnFlag = false; // 批量
        console.log("批量会员重新生成二维码");
        let data = {
          ids: this.ids,
          createFlag: this.createFlag
        }
        createCodeAndPostAll(data).then(res => {
          if (res.code == 200) {
            this.getList();
            this.$modal.msgSuccess("批量重新生成成功！");
          }
        })
      }
      this.createMiniFlag = false;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        superReferralCode: null,
        referralCode: null,
        memberExpireDate: null,
        disable: null,
        recommendedPoster: null,
        smallShareQrcode: null,
        extractableDays: null,
        drawnDays: null,
        renewalTime: null,
        memberPhone: null,
        createTime: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加会员管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getMember(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改会员管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateMember(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMember(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除会员管理编号为"' + ids + '"的数据项？').then(function () {
        return delMember(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('funct/member/export', {
        ...this.queryParams
      }, `member_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
